package com.heima.admin.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.admin.mapper.LoginMapper;
import com.heima.admin.service.LoginService;
import com.heima.model.admin.dtos.AdminLoginDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;

/**
 * @Description TODO
 * @Author earl
 * @Data 2024/8/21上午10:54
 * @Version 1.0
 */
@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private LoginMapper loginMapper;

    /**
     * 登录请求
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(AdminLoginDto dto) {
        if (dto.getName().isEmpty() || dto.getPassword().isEmpty()){
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_NULL);
        }
        LambdaQueryWrapper<AdUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AdUser::getName, dto.getName());
        AdUser adUser = loginMapper.selectOne(wrapper);
        if(adUser ==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        String salt = adUser.getSalt();
        String encode = DigestUtils.md5DigestAsHex((dto.getPassword() + salt).getBytes());
        if(!encode.equals(adUser.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        String token = AppJwtUtil.getToken(adUser.getId().longValue());
        adUser.setPassword("");
        adUser.setSalt("");
        HashMap<String, Object> map = new HashMap<>();
        map.put("user", adUser);
        map.put("token",token);
        return ResponseResult.okResult(map);
    }
}